package com.dzm.filter;

import com.dzm.constants.RedisConstant;
import com.dzm.properties.SecurityIgnoreProperties;
import com.dzm.utils.JwtUtil;
import com.dzm.utils.ResponseUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 作者：Dzm
 * 时间：2024-08-23-10:46
 * 功能：
 */

@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private SecurityIgnoreProperties securityIgnoreProperties;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        if(securityIgnoreProperties.getWhites().contains(url)) {
            //白名单中的路径直接放行
            return chain.filter(exchange);
        }

        //解析前端传来的token
        String token = request.getHeaders().getFirst("Authorization").replace("Bearer ", "");
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String uuid = (String) claims.get("user_key");
        String key = RedisConstant.LOGIN_TOKEN + uuid;
        Boolean hasKey = redisTemplate.hasKey(key);
        //如果前端有该key则放行
        if(!hasKey) {
            return ResponseUtil.webFluxResponseWriter(response, "登录失败");
        }

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
